const   exp = require('express'),
        bodyParser = require('body-parser'),
        cookieParser = require('cookie-parser'),
        fs = require('fs'),
        multer = require('multer'),
        template = require('art-template'),
        app = exp()
        
        
const   storage = multer.diskStorage({
            destination: 'www/uploads',
            filename: function(req, file, callback){
                var petname = req.cookies.petname
                callback(null, `${petname}.jpg`)
            }
        }),
        uploads = multer({storage})
        
        
app.use(exp.static('www'))
app.use(bodyParser.urlencoded({extended:true}))
app.use(cookieParser())

app.engine('html', require('express-art-template'))

template.defaults.imports.ms = function(t){
    t = new Date(t)
    return t.getTime()
}
template.defaults.imports.formatTime = function(t){
    t = new Date(t)
    
    var M = t.getMonth() + 1,
        d = t.getDate(),
        h = t.getHours(),
        m = t.getMinutes()

    M = M < 10 ? '0' + M : M
    d = d < 10 ? '0' + d : d
    h = h < 10 ? '0' + h : h
    m = m < 10 ? '0' + m : m
    
    return t.getFullYear() + '-' + M + '-' + d + ' ' + h + ':' + m
}


function send(res, code, message, data){
    res.status(200).json({code, message, data})
}

function sign(req, res, next){
    if(req.cookies.petname){
        // 有用户登录时调用next
        next()
    }
    else{    
        // 重定向到登录页面
        res.redirect('/user/signin')
    }
}

/*--------------------注册--------------------*/
app.get('/user/register', (req, res) => {
    res.render('user/register.html', {
        title: '用户注册'
    })
})

app.post('/user/register', (req, res) => {
    req.body.ip = req.ip
    req.body.time = new Date()
    
    function saveFile(){
        var fileName = `users/${req.body.petname}.txt`
        
        fs.exists(fileName, exists => {
            if(exists){
                send(res, 'registered', '用户名已经注册过了！')
            }
            else{
                fs.appendFile(fileName, JSON.stringify(req.body), err => {
                    if(err){
                        send(res, 'file error', '抱歉，系统错误...')
                    }
                    else{
                        send(res, 'success', '恭喜，注册成功！请登录...')
                    }
                })
            }
        })
    }
   
    fs.exists('users', exists => {
        if(exists){
            saveFile()
        }
        else{
            fs.mkdir('users', err => {
                if(err){
                    send(res, 'file error', '抱歉，系统错误...')
                }
                else{
                    saveFile()
                }
            })
        }
    })
})

/*--------------------登录--------------------*/

app.get('/user/signin', (req, res)=>{
    res.render('user/signin.html', {
        title: '登录',
        rightNav: 'register'
    })
})

app.post('/api/user/signin', (req, res) => {
    var fileName = `users/${req.body.petname}.txt`
        
    fs.exists(fileName, exists => {
        if(exists){
            fs.readFile(fileName, (err, data) => {
                if(err){
                    send(res, 'file error', '抱歉，系统错误...')
                }
                else{
                    var user = JSON.parse(data)
                    if(user.password == req.body.password){
                        
                        res.cookie('petname', req.body.petname)
                        // 此处需要加密
                        
                        send(res, 'success', '登录成功...')
                    }
                    else{
                        send(res, 'signin error', '用户名或密码错误！')
                    }
                }
            })
        }
        else{
            send(res, 'register error', '用户名未注册！')
        }
    })
})

/*--------------------退出--------------------*/

app.get('/user/signout', (req, res) => {
    res.clearCookie('petname')
    res.redirect('/')
    // 在服务端控制浏览器页面跳转
    // 重定向
})

/*--------------------提问--------------------*/
// 添加sign请求处理函数
// 判断用户是否登录，如果未登录则重定向到登录页
// 如果已登录则交给后面箭头函数处理
app.get('/ask', sign, (req, res) => {
    res.render('ask.html', {
        title: '提问'
    })
})

app.post('/ask', sign, (req, res) => { 
    var petname = req.cookies.petname
     
    if(!petname){
        send(res, 'signin error', '请重新登录...')
        return
    }
    
    var time = new Date()
    
    req.body.petname = petname
    req.body.ip = req.ip
    req.body.time = time
    
    function saveFile(){
        var fileName = `questions/${time.getTime()}.txt`
        
        fs.appendFile(fileName, JSON.stringify(req.body), err => {
            if(err){
                send(res, 'file error', '抱歉，系统错误...')
            }
            else{
                send(res, 'success', '问题提交成功！')
            }
        })
    }
    
    fs.exists('questions', exists => {
        if(exists){
            saveFile()
        }
        else{
            fs.mkdir('questions', err => {
                if(err){
                    send(res, 'file error', '抱歉，系统错误...')
                }
                else{
                    saveFile()
                }
            })
        }
    })
})

/*--------------------头像--------------------*/
app.get('/user/photo', sign, (req, res) => {
    res.render('user/photo.html', {
        title: '修改头像'
    })
})
app.post('/user/photo', sign, uploads.single('photo'), (req, res) => {
    res.status(200).json({ code: 'success', message: '上传成功' })
})

/*--------------------首页--------------------*/


app.get('/', (req, res) => {
    function readFiles(i, files, questions, complete){
        if(i < files.length){
            fs.readFile(`questions/${files[i]}`, (err, data) => {
                if(!err){
                    // questions是传入的空数组
                    // 它存放的是读取成功以后的文件内容
                    questions.push(JSON.parse(data))
                }
                readFiles(++i, files, questions, complete)
            })
        }
        else{
            // 全部读取完毕后调用complete
            // 它的作用是把读取的数据用来渲染首页
            complete()
        }
    }
    
    fs.readdir('questions', (err, files) => {
        if(err){
            // 跳转到错误页
        }
        else{
            // files是读取文件夹成功后，所有文件名组成数组
            files = files.reverse()
            console.log(files)
            var questions = []
            
            readFiles(0, files, questions, () => {
                res.render('index.html', {
                    user: req.cookies.petname,
                    questions
                })
            })
        }
    })
})

/*--------------------回答--------------------*/
app.get('/answer/:question', sign, (req, res) => {
    res.render('answer.html', {
        title: '回答',
        question: req.params.question
    })
})

app.post('/answer', sign, (req, res) => { 
    var petname = req.cookies.petname
    
    if(!petname){
        send(res, 'signin error', '请重新登录...')
        return
    }
    console.log(req.body)
    var filename = `questions/${req.body.question}.txt`
    
    req.body.petname = petname
    req.body.ip = req.ip
    req.body.time = new Date()
    
    fs.readFile(filename, (err, data) => {
        if(err){
            send(res, 'file error', '抱歉，系统错误...')
        }
        else{
            var question = JSON.parse(data)
            if(!question.answers) question.answers = []
            
            question.answers.push(req.body)
            
            fs.writeFile(filename, JSON.stringify(question), err => {
                if(err){
                    send(res, 'file error', '抱歉，系统错误...')
                }
                else{
                    send(res, 'success', '回答提交成功！')
                }
            })
        }
    })
})

/*--------------------监听--------------------*/

app.listen(3000, () => console.log('正在运行...'))